// https://leetcode.cn/problems/number-of-subarrays-with-bounded-maximum/
#include <iostream>
#include <vector>
// 给你一个整数数组 nums 和两个整数：left 及 right 。找出 nums 中连续、非空且其中最大元素在范围 [left, right] 内的子数组，并返回满足条件的子数组的个数。

using namespace std;
class Solution
{
public:
    // 自己的解法
    int numSubarrayBoundedMax1(vector<int> &nums, int left, int right)
    {
        int l = -1, r = 0, n = nums.size(), tmp = 0;
        int count = 0;
        while (r < n)
        {
            if (nums[r] < left)
            {
                if (l == -1)
                    l = r;
                else
                    count += tmp;
                r++;
            }
            else if (nums[r] >= left && nums[r] <= right)
            {
                if (l == -1)
                    l = r;
                tmp = r - l + 1;
                count += tmp;
                r++;
            }
            else
            {
                r++;
                l = -1;
                tmp = 0;
            }
        }
        return count;
    }
    // 官方解法
    int numSubarrayBoundedMax(vector<int> &nums, int left, int right)
    {
        int l = -1, r = -1, count = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] >= left && nums[i] <= right)
            {
                r = i;
            }
            else if (nums[i] > right)
            {
                l = i;
                r = -1;
            }
            if (r != -1)
            {
                count += r - l;
            }
        }
        return count;
    }
};

int main()
{
    Solution so;
    vector<int> nums = {73, 55, 36, 5, 55, 14, 9, 7, 72, 52};
    cout << so.numSubarrayBoundedMax(nums, 32, 69);
    return 0;
}